<script lang="ts">
import type { BonusDetailType } from '~/components-business/global-popups/newWallet/ts/depositBonusInfoHook';
import { useActivityWelcomeBonus } from '~/components-business/global-popups/newWallet/ts/depositBonusInfoHook';
import { useReadyAll } from '~/components-business/global-popups/newWallet/ts/useReadyAll';
import Countdown from './Countdown.vue';

export interface WelcomeBonusDetProps {
  size?: 'small' | 'large';
  onQuestion?: (item: BonusDetailType) => void;
};

export function useWelcomeBonusData(
  isSmall: ComputedRef<boolean>,
  scrollDom: Ref<HTMLElement | null>,
  questionFn: WelcomeBonusDetProps['onQuestion'],
) {
  const { getBonusListRef, getCryptoNameRef, refetchActivity } = useActivityWelcomeBonus();

  const countDownFinishList = ref<[boolean, boolean][]>([]);

  watch(getBonusListRef, (v) => {
    countDownFinishList.value = v.length
      ? v.map(x => [!x.timeInfo.isInBoostExpireSecond, !x.timeInfo.isInExpireSecond])
      : [];
  }, { immediate: true });

  function findCountDownItemToIdx(idx: number) {
    const list = countDownFinishList.value;
    return list.length ? list[idx] : void 0;
  }

  function onCountDownFinish(idx: number, isBoost = true) {
    const item = findCountDownItemToIdx(idx);
    if (item) {
      item[isBoost ? 0 : 1] = true;
      refetchActivity();
    }
  }

  const getBonusItemsRef = computed(() => getBonusListRef.value.map((x, i) => ({
    ...x,
    isCountDownBoost: findCountDownItemToIdx(i)?.[0] === true,
    isCountDownBonust: findCountDownItemToIdx(i)?.[1] === true,
  })));

  const { depositReadyQry, refetchDepositReady } = useReadyAll();

  refetchDepositReady();

  const getDecimalsRef = computed(() => {
    const list = toValue(depositReadyQry?.data)?.currency_balance_list || [];
    const find = list.find(x => getCryptoNameRef.value && x.currency === getCryptoNameRef.value);
    const minDepositAmount = Math.min(...(find?.tokens || []).map(x => bignumber(x.min_deposit_amount || 0).toNumber()));
    return bignumber(minDepositAmount || 0).decimalPlaces() ?? void 0;
  });

  function clickQuestion(item: BonusDetailType) {
    if (isSmall.value && typeof questionFn === 'function') {
      questionFn(item);
      return;
    }
    const { cryptoName, fiatMap } = useCurrencyStore();
    const isFiat = !!cryptoName && Object.keys(fiatMap || {}).includes(cryptoName);
    globalPopups?.welcomeBonusPopup?.open({ detailData: item, decimals: getDecimalsRef.value, isFiat });
  }

  async function scrollToTargetRow() {
    await nextTick();

    const cardDom = toValue(scrollDom);
    const findIdx = getBonusItemsRef.value.findIndex(x => x.available);
    const find = findIdx > -1 ? getBonusItemsRef.value[findIdx] : null;

    const targetRowEl = find?.rowkey ? cardDom?.querySelector<HTMLElement>(`[rowkey="${find?.rowkey}"]`) : void 0;

    if (!cardDom || (cardDom?.scrollLeft ?? 0) > 0 || !targetRowEl || findIdx < 1)
      return;

    const paddingLeft = findIdx + 1 < getBonusItemsRef.value.length ? 10 : 0;

    const left = targetRowEl.offsetLeft - paddingLeft;

    left > 0 && cardDom?.scrollTo({ left, behavior: 'instant' as ScrollBehavior });
  }

  watch([getBonusListRef, isSmall], ([a, b]) => a.length && b && scrollToTargetRow());

  onMounted(() => isSmall.value && scrollToTargetRow());

  return {
    getBonusItemsRef,
    onCountDownFinish,
  };
}
</script>

<script lang="ts" setup>
const props = withDefaults(defineProps<WelcomeBonusDetProps>(), { size: 'small' });

const getIsSmallRef = computed(() => props.size === 'small');

const scrollDomRef = ref<HTMLElement | null>(null);

const { getBonusItemsRef, onCountDownFinish } = useWelcomeBonusData(getIsSmallRef, scrollDomRef, props.onQuestion);

const bonusRateText = computed(() => getBonusItemsRef.value.map(item => item.maxInfo.bonustRateText));
</script>

<template>
  <div class="relative h-full flex-1">
    <div
      ref="scrollDomRef"
      class="w-full flex gap-2.5"
      :class="getIsSmallRef ? 'scroll-dom-cls px-3' : 'px-5'"
    >
      <div v-for="(item, idx) of getBonusItemsRef" :key="item.rowkey" :rowkey="item.rowkey" class="bonus-card">
        <div
          v-if="item.available" class="bonus-card-content bonus-card-content-active flex-wrap gap-2 text-center"
          :class="getIsSmallRef ? 'px-2 py-4' : 'px-12.5 py-5'"
        >
          <div class="w-full">
            <div class="text-center text-3.5 text-slate-200">
              {{ item.title }}
              <!-- <i class="i-ri:question-line mb-0.5 ml-0.5 cursor-pointer text-4" @click="clickQuestion(item)" /> -->
            </div>

            <template v-if="!getIsSmallRef && item.timeInfo.isInBoostExpireSecond && !item.isCountDownBoost">
              <div class="mt-1 flex-center gap-2 text-3 text-slate-200">
                <span class="text-brand line-through"><em class="text-slate-200">{{ bonusRateText[idx] }}</em></span>
                <span class="text-white font-700">
                  {{ $t('efoNcLqwIEylHaLUt3yxs') }}
                </span>
              </div>
              <div class="bonus-card-details max-w-100% px-2.5">
                <div class="flex items-center gap-1 text-4 font-900">
                  <i class="i-local:bonus__card-icon h-4 w-4" />
                  {{ item.maxInfo.boostRateText }}
                </div>
                <div class="divider-v-gradual-white" />
                <Countdown :value="item.timeInfo.boostExpireDate" @finish="onCountDownFinish(idx)">
                  <template #default="{ diff, formatText }">
                    <span v-if="diff.d > 0 || diff.h > 0" class="!text-[13px]">{{ formatText((diff.d * 24) + diff.h, ':') }}</span>
                    <span class="!text-[13px]">{{ `${formatText(diff.m, ':')}${formatText(diff.s)}` }}</span>
                  </template>
                </Countdown>
              </div>
            </template>

            <template v-else-if="getIsSmallRef && item.timeInfo.isInBoostExpireSecond && !item.isCountDownBoost">
              <div class="bonus-card-details max-w-100% px-2.5">
                <div class="flex items-center gap-1.5 text-4 font-900">
                  <i class="i-local:bonus__card-icon h-4 w-4" />
                  {{ item.maxInfo.boostRateText }}
                </div>
                <span class="ml-1.5 text-3 text-brand line-through"><em class="text-slate-200">{{ bonusRateText[idx] }}</em></span>
                <div class="divider-v-gradual-white" />
                <Countdown :value="item.timeInfo.boostExpireDate" @finish="onCountDownFinish(idx)">
                  <template #default="{ diff, formatText }">
                    <span v-if="diff.d > 0 || diff.h > 0" class="!text-3">{{ formatText((diff.d * 24) + diff.h, ':') }}</span>
                    <span class="!text-[13px]">{{ `${formatText(diff.m, ':')}${formatText(diff.s)}` }}</span>
                  </template>
                </Countdown>
              </div>
            </template>

            <div
              v-else-if="bonusRateText[idx]"
              class="mt-1 flex items-center justify-center gap-2 text-left text-white font-700 leading-normal"
              :class="getIsSmallRef ? ' text-5' : ' text-8'"
            >
              {{ bonusRateText[idx] }}
              <span class="text-3 text-slate-200 font-400">
                {{ $t('efoNcLqwIEylHaLUt3yxs') }}
              </span>
            </div>
          </div>

          <div class="w-full flex gap-1.5">
            <div
              v-if="item.timeInfo.isInExpireSecond && !item.isCountDownBonust"
              class="w-full flex-center border-(1px sys-layer-e solid) rounded-2 py-1 text-center !text-slate-200"
            >
              <Countdown :class="getIsSmallRef ? '!text-xs' : '!text-[13px]'" :value="item.timeInfo.expireDate" @finish="onCountDownFinish(idx, false)">
                <template #default="{ diff, formatText }">
                  <span v-if="diff.d > 0">{{ formatText(diff.d, 'd ', false) }}</span>
                  <span>{{ `${formatText(diff.h, ':')}${formatText(diff.m, ':')}${formatText(diff.s)}` }}</span>
                </template>
              </Countdown>
            </div>
            <AButton
              class="ant-cover__Button-3d-primary mt-0 !h-8.5 !w-full !flex-center"
              type="primary" block @click="item.toDeposit"
            >
              {{ $t('p9zKloGqNTkIgC4asiQrx') }}
            </AButton>
          </div>
        </div>

        <div
          v-else class="bonus-card-content flex-wrap gap-2 text-center"
          :class="getIsSmallRef ? 'px-2 py-4' : 'px-12.5 py-5'"
        >
          <div class="min-w-43">
            <div class="text-center text-3.5 text-slate-200">
              {{ item.title }}
            </div>
            <div
              class="mt-1 flex items-center justify-center gap-2 text-left text-white font-700 leading-normal"
              :class="getIsSmallRef ? ' text-5' : ' text-8'"
            >
              {{ bonusRateText[idx] }}
              <span class="text-3 text-slate-200 font-400">
                {{ $t('efoNcLqwIEylHaLUt3yxs') }}
              </span>
            </div>
          </div>
          <div class="w-full">
            <AButton
              class="ant-cover__Button-3d-primary mt-1 !h-8.5 !flex-center"
              type="primary"
              disabled block
            >
              {{ $t('p9zKloGqNTkIgC4asiQrx') }}
            </AButton>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.bonus-card {
  --uno: 'rounded-3 overflow-hidden flex relative w-full lt-tablet:min-w-55 ';
}
.bonus-card-content {
  opacity: 70%;
  background: radial-gradient(93.08% 76.67% at 50% 0%, rgba(221, 222, 228, 0.2) 0%, rgba(29, 30, 36, 0.2) 100%),
    radial-gradient(110.89% 110.89% at 50% -10.89%, rgba(221, 222, 228, 0.2) 0%, rgba(0, 0, 0, 0) 100%), #000;
  --uno: 'rounded-2 flex-center grid-cols-[auto_1fr] h-full w-full';
}
.bonus-card-content-active {
  background: radial-gradient(62.89% 76.67% at 50% 0%, rgba(59, 130, 246, 0.4) 0%, rgba(29, 30, 36, 0.4) 100%),
    radial-gradient(68.13% 110.89% at 50% -10.89%, rgba(59, 130, 246, 0.3) 0%, rgba(132, 138, 157, 0) 100%), #000;
  opacity: 100%;
  &::before {
    background-image: url('../../imgs/light.png');
    background-size: 100% 100%;
    content: '';
    height: 100%;
    left: 20px;
    right: 20px;
    height: 20px;
    pointer-events: none;
    position: absolute;
    top: 0;
  }
}
.bonus-card-details {
  --uno: 'rounded-1 flex p-1 flex-center mt-1 h-7.5';
  background: linear-gradient(90deg, rgba(58, 122, 228, 0.6) 0%, rgba(38, 67, 114, 0.6) 100%);
}
.divider-v-gradual-white {
  background-image: linear-gradient(rgba(75, 85, 99, 0.1) 0%, #dddee4 50.5%, rgba(75, 85, 99, 0.1) 100%);
  --uno: 'w-[1px] !mx-3 lt-tablet:!mx-1 h-6';
}

.scroll-dom-cls {
  overflow-x: auto !important;
  scrollbar-width: none !important;
  &::-webkit-scrollbar {
    width: 0 !important;
    height: 0 !important;
    display: none !important;
  }
  -ms-overflow-style: none !important;
  overflow: -moz-scrollbars-none;
}
</style>
